<?php

class Login extends CI_Controller{
    function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->library('form_validation');
        
    }
    function index() {
        $this->load->model('user');
        $this->load->helper(array('url','form'));
        if ($this->user->check_user())
        {
            redirect('nhanvien/home');
        }
        else
        {   
            $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
            if ($this->form_validation->run($this) == FALSE) {
                   $this->load->view('nhanvien/login_view',$data='');
            } else {
                   redirect('nhanvien/home');
            }
        }
    }
    function check_database($password) {
        $username = $this->input->post('username');
       
        $this->load->model('nhanvien_model');
        
        $result = $this->nhanvien_model->login($username, $password)->row_array();
        if (count($result)>0) {
            $sess_array = array('id' => $result['MSNV'],'sign_in' => TRUE,'type'=>2060);
            $this->session->set_userdata('login_data', $sess_array);
            return TRUE;
        } else {
            $this->form_validation->set_message('check_database', 'Invalid username or password');
            return FALSE;
        }
    }
    function logout(){
        $this->load->helper('url');
        $this->session->unset_userdata('login_data');
        redirect('nhanvien/login', 'refresh');
        session_destroy();
    }
}
